package base;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.io.FileHandler;

import java.io.*;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

public class Base {

    Properties prop = new Properties();
    public WebDriver driver;

    /**
     * 启动浏览器
     *
     * @throws Exception
     */
    public void starBrowser() throws Exception {

        //读取Globaldata配置文件的内容
        File file = new File("Configs/GlobalData.properties");

        if (file.exists())
            prop.load(new FileReader(file));
        else {
            System.out.println("配置文件不存在!");
            return;
        }

        //获取配置文件里的browser
        String browser = prop.getProperty("browser");
        String driverpath = "G:\\idea_java_project\\";
        try {
            if (browser.equals("firefox")) {
                System.setProperty("webdriver.gecko.driver", driverpath + "geckodriver.exe");
//                System.setProperty("webdriver.gecko.driver", "src/main/resources/geckodriver.exe");
                //打开浏览器
                driver = new FirefoxDriver();
            } else if (browser.equals("chrome")) {
                System.setProperty("webdriver.chrome.driver", driverpath + "chromedriver.exe");
                //打开浏览器
                driver = new ChromeDriver();
            }
        } catch (Exception e) {
            System.out.println(e + "找不到浏览器驱动!");
        }
//        else if (browser.equals("Ie")) {
//            System.setProperty("", "");
//            //打开浏览器
//            WebDriver driver = new InternetExplorerDriver();
//        }

        //获取url
        String url = prop.getProperty("url");
        driver.get(url);
        //隐式等待10秒  如果页面加载慢就等待页面加载
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);


    }

    /**
     * 截图方法
     */
    public void takeScreenshot(String screenShotName, WebDriver driver) throws IOException {
        //定义TakesScreenshot引用变量，将当前的driver实力转换为TakesScreenshot
        TakesScreenshot ts = (TakesScreenshot) driver;
        //调用getScreenshotAs方法实现截图，截图保存在临时文件夹中
        File srcFile = ts.getScreenshotAs(OutputType.FILE);
        //user.dir不管你放在那个盘都能获取到Screenshot文件夹保存截图
        File desFile = new File(System.getProperty("user.dir") + "//Screenshot//" + screenShotName + ".png");
        FileHandler.copy(srcFile, desFile);
    }
}
